package com.xx.doublexchat.common.user.adapter;

import cn.hutool.core.bean.BeanUtil;
import com.xx.doublexchat.common.common.domain.enums.YesOrNoEnum;
import com.xx.doublexchat.common.user.domain.entity.ItemConfig;
import com.xx.doublexchat.common.user.domain.entity.User;
import com.xx.doublexchat.common.user.domain.entity.UserBackpack;
import com.xx.doublexchat.common.user.domain.vo.response.BadgesResponse;
import com.xx.doublexchat.common.user.domain.vo.response.UserInfoResponse;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import org.apache.commons.beanutils.BeanUtils;

import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

public class UserAdapter {
    public static User buildUser(String openId) {
        return User.builder().openId(openId).build();
    }

    public static User buildUserAuthorizeUser(User user, WxOAuth2UserInfo userInfo) {
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setName(userInfo.getNickname());
        updateUser.setAvatar(userInfo.getHeadImgUrl());
        return updateUser;
    }

    /**
     * 构造userInfo对象
     *
     * @param user
     * @param modifyNameCount
     * @return
     */
    public static UserInfoResponse buildUserInfo(User user, Integer modifyNameCount) {
        UserInfoResponse vo = new UserInfoResponse();
        BeanUtil.copyProperties(user, vo);
        vo.setModifyNameChance(modifyNameCount);
        return vo;
    }

    /**
     * 组装徽章
     * @param itemConfigs --- 物品缓存
     * @param userBackpacks --- 用户背包信息
     * @param user --- 用户信息
     * @return
     */
    public static List<BadgesResponse> buildBadgeResp(List<ItemConfig> itemConfigs,
                                                      List<UserBackpack> userBackpacks,
                                                      User user) {
        // 获取用户拥有的徽章id
        Set<Long> obtainItemSet = userBackpacks.stream()
                .map(UserBackpack::getItemId).collect(Collectors.toSet());

        return itemConfigs.stream().map(a -> {
            BadgesResponse resp = new BadgesResponse();
            BeanUtil.copyProperties(a,resp);
            // 判断用户是否拥有该勋章
            resp.setObtain(obtainItemSet.contains(a.getId()) ? YesOrNoEnum.YES.getStatus() : YesOrNoEnum.NO.getStatus());
            // 判断用户是否佩戴该勋章
            resp.setWearing(Objects.equals(a.getId(),user.getItemId()) ? YesOrNoEnum.YES.getStatus() : YesOrNoEnum.NO.getStatus());
            return resp;
        }).sorted(Comparator.comparing(BadgesResponse::getWearing, Comparator.reverseOrder()) //对是否佩戴做降序
                .thenComparing(BadgesResponse::getObtain,Comparator.reverseOrder())) // 对是否拥有做降序
                .collect(Collectors.toList());
    }
}
